import {saveAs} from 'file-saver'

import { MessagePlugin } from 'tdesign-vue-next';
import { request } from './index';


// 严重是否为Blob数据
const isBlobData = async (data:any)=> {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}
export function download(url: any, params: any, filename: any) {
    return request.post({ url, data: params, responseType: 'blob' }).then(async (data: any) => {
            const isLogin = await isBlobData(data);
            if (isLogin) { // 如果是Blob数据  
                const blob = new Blob([data],{ type: "application/vnd.ms-excel" }); // 第二个参数为下载的文件的类型
                saveAs(blob, filename);// 调用方法下载
            } else {
                const resText = await data.text();
                const rspObj = JSON.parse(resText);
                const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode.default;
                MessagePlugin.error(errMsg);
            }
        })
        .catch((r) => {
            console.error(r);
            MessagePlugin.error('下载文件出现错误，请联系管理员！');
        });
}